#include "StdAfx.h"
#include "SDLSound.h"

CSDLSound::CSDLSound() : CSound()
{
audioBuffer = NULL;
audio_callback = NULL;
user = 0;
}

void CSDLSound::Pause()
{
SDL_PauseAudio(1);
}

void CSDLSound::Resume()
{
SDL_PauseAudio(0);
}

int CSDLSound::Play()
{
return(0);
}

static void sdl_audio_player(void *udata, unsigned char *stream, int len)
{
CSDLSound *Sound = (CSDLSound*)udata;

if(16 == Sound->sound_bps)
   len /= 2;
if(Sound->audio_callback)
   Sound->audio_callback(Sound->user,stream,len);
}

int CSDLSound::Init(u8 *buffer,u32 bufsize,u32 bits,u32 hz)
{
SDL_AudioSpec wanted,obtained;
unsigned int bufferSize;

sound_bps = 16;
sound_samplerate = 44100;
sound_fragsize = 1024;
if(SDL_InitSubSystem(SDL_INIT_AUDIO) == -1)
	{
	message("error initializing sdl audio\n");
	return(0);
	}
wanted.freq = 44100;
wanted.format = AUDIO_S16;
wanted.channels = 1;   /* 1 = mono, 2 = stereo */
wanted.samples = sound_fragsize;
wanted.callback = sdl_audio_player;
wanted.userdata = this;
if(SDL_OpenAudio(&wanted,&obtained) < 0)
	{
	message("Couldn't open audio: %s\n", SDL_GetError());
	return(0);
   }
if(AUDIO_S16 != obtained.format)
	{
	message("Could not get correct audio output format\n");
	return(1);
	}
sound_bps = (obtained.format == AUDIO_U8) ? 8 : 16;
sound_samplerate = obtained.freq;
bufferSize = (sound_bps / 8) * obtained.samples * 2;
audioBuffer = new unsigned char[bufferSize];
if(NULL == audioBuffer)
   {
	message("error allocating audio buffer\n");
	return(1);
   }
SDL_PauseAudio(0);
audio_callback = 0;
message("sdl sound init ok, %dhz, %d bits\n",sound_samplerate,sound_bps);
return(0);
}

void CSDLSound::Kill()
{
SDL_CloseAudio();
SDL_QuitSubSystem(SDL_INIT_AUDIO);
}
